<template>
  <div class="addSite">
    <div class="mains_contain">
      <el-form label-position="left" :model="searchForm" label-width="80px" class="addForm" :rules="rule" size="small" ref="searchForm">
        <el-form-item label="租户" prop="tenantId">
          <el-select v-model="searchForm.tenantId" style="width: 600px" clearable placeholder="请选择">
            <el-option :label="item.name" v-for="item in tenantList" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="站点名称" prop="baseAreaId">
          <!-- :props="{ checkStrictly: true }" -->
          <el-cascader :options="options" clearable v-model="searchForm.baseAreaId" style="width: 600px" @expand-change="change" @change="change"></el-cascader>
        </el-form-item>
        <el-form-item label="站点类型" prop="sitesType">
          <el-input v-model="searchForm.sitesType" style="width: 600px" @input="changeName"></el-input>
        </el-form-item>
        <el-form-item label="站点描述">
          <el-input v-model="searchForm.sitesRemarks" rows="4" placeholder="长度不超过200字" maxlength="200" type="textarea" style="width: 600px" @input="changes"></el-input>
          <div style="text-align: left;"><span>{{ searchForm.sitesRemarks && searchForm.sitesRemarks.trim().length || 0   }}</span>/200</div>
        </el-form-item>

        <el-button type="success" size="mini" @click="handlerAdd" icon="el-icon-plus">添加设备</el-button>
        <div class="contant">
          <el-table :data="tableData1" style="width: 100%; margin-top: 10px" @selection-change="handleSelectionChange" fit max-height="460px" border stripe size="mini" highlight-current-row
            :header-cell-style="{ background: '#e5e5e5', color: '#000' }">
            <el-table-column prop="name" label="设备名称" />
            <el-table-column prop="nodeId" label="设备标识" show-overflow-tooltip />
            <el-table-column prop="url" label="公司名称" />
            <el-table-column prop="url" label="设备型号" />
            <el-table-column prop="url" label="芯片型号" />
            <el-table-column prop="url" label="操作系统" />
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-delete" @click="onCanle(scope.row, scope.$index)" style="color:#F56C6C">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="text-align: right; margin-top: 20px; margin-right: 20px">
            <el-pagination layout="total" :total="tableData1.length" v-if="tableData1.length > 0">
            </el-pagination>
          </div>
        </div>
        <div style="text-align: left; margin-top: 30px">
          <el-button type="primary" @click="submitForm" size="small">保存</el-button>
          <el-button @click="cancle" size="small">取消</el-button>
        </div>
      </el-form>
    </div>
    <!-- //添加设备组 -->
    <el-dialog title="选择需要添加的设备" :visible.sync="dialogVisible" width="80%" :close-on-click-modal="false" @close="close" v-if="dialogVisible">
      <el-form :inline="true" :model="searchSite" size="small" label-width="80px">
        <el-form-item label="设备名称">
          <el-input v-model="searchSite.name" clearable placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备标识">
          <el-input v-model="searchSite.nodeId" clearable placeholder="请输入设备标识" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="qureySearch" size="mini" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="contant" style="margin-top: 10px">
        <el-table ref="multipleTable" :data="lists" style="width: 100%" @selection-change="handleSelectionChangeDiaog" fit :max-height="maxHeight" border stripe size="mini" highlight-current-row
          :header-cell-style="{ background: '#e5e5e5', color: '#000' }">
          <el-table-column type="selection" width="40" :selectable="selectable" />
          <el-table-column prop="name" label="设备名称" show-overflow-tooltip />
          <!-- <el-table-column prop="tenantTxt" label="租户" min-width="110" /> -->
          <el-table-column prop="nodeId" label="设备标识" show-overflow-tooltip />
          <el-table-column prop="url" label="公司名称" />
          <el-table-column prop="url" label="设备型号" />
          <el-table-column prop="url" label="芯片型号" />
          <el-table-column prop="url" label="操作系统" />
          <!-- <el-table-column prop="nodeType" label="节点类型">
            <template slot-scope="scope">
              <el-tag
                effect="dark"
                size="mini"
                v-if="scope.row.nodeType == 'ENDPOINT'"
                >终端设备</el-tag
              >
              <el-tag
                effect="dark"
                size="mini"
                v-if="scope.row.nodeType == 'GATEWAY'"
                >网关设备</el-tag
              >
              <el-tag
                effect="dark"
                size="mini"
                v-if="scope.row.nodeType == 'UNKNOW'"
                >未知设备</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="protocolType"
            label="协议类型"
            show-overflow-tooltip
          />
          <el-table-column prop="status" label="设备状态">
            <template slot-scope="scope">
              <el-tag
                effect="dark"
                size="mini"
                type="success"
                v-if="scope.row.status == 'ONLINE'"
                >在线</el-tag
              >
              <el-tag
                effect="dark"
                size="mini"
                type="danger"
                v-if="scope.row.status == 'OFFLINE'"
                >离线</el-tag
              >
              <el-tag
                effect="dark"
                size="mini"
                type="warning"
                v-if="scope.row.status == 'INACTIVE'"
                >未注册</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="mute" label="设备是否冻结">
            <template slot-scope="scope">
              <el-tag
                effect="dark"
                size="mini"
                v-if="scope.row.mute == 'FALSE'"
                type="success"
                >否</el-tag
              >
              <el-tag
                effect="dark"
                size="mini"
                v-if="scope.row.mute == 'TRUE'"
                type="danger"
                >是</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="110">
          </el-table-column> -->
        </el-table>
        <div style="text-align: right">
          <pagination v-show="pagination.total > 0" :limit.sync="pagination.pageSize" :page.sync="pagination.page" :total="pagination.total" @pagination="getPageList1" />
        </div>
      </div>
      <div style="text-align: right; margin-top: 30px">
        <el-button type="primary" @click="submitOk" size="small">保存</el-button>
        <el-button @click="close" size="small">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as api from "@/api/link/device";
import {
  baseArea,
  siteSave,
  pageByTenantId,
  details,
  siteUpdate,
} from "@/api/site/site";
import * as tenantApi from "@/api/sys/tenant";
export default {
  data() {
    let account = /^[\u4e00-\u9fa5a-zA-Z-z0-9]+$/
    const validateName = (rule, value, callback) => {
      if (value == "" || !value) {
        callback(new Error("请输入站点类型"));
      } else {
        if (account.test(value)) {
          callback();
        } else {
          callback(new Error("站点类型不能出现特殊字符"));
        }
      }
    };
    return {
      dialogVisible: false,
      searchForm: {},
      searchSite: {},
      tenantList: [],
      options: [],
      rule: {
        tenantId: [
          { required: true, message: "请选择租户", trigger: "change" },
        ],
        baseAreaId: [
          { required: true, message: "请选择站点名称", trigger: "change" },
        ],
        sitesType: [
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' },
          { required: true, trigger: "blur", validator: validateName },

        ],
        // sitesType: [
        //   { required: true, message: "请输入站点类型", trigger: "blur" },
        // ],
      },
      pagination: {
        total: 0,
        page: 1,
        pageSize: 10,
      },
      pagination1: {
        total: 0,
        page: 1,
        pageSize: 10,
      },
      tableData: [],
      tableData1: [],
      checkList: [],
      deviceNodeIdList: [],
    };
  },
  computed: {
    maxHeight() {
      var curHeight =
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight;
      return curHeight - 280;
    },
    lists() {
      let arr = [];
      this.tableData1.forEach((item) => {
        arr.push(item.id);
      });
      this.tableData.forEach((res) => {
        if (arr.indexOf(res.id) > -1) {
          res.disabled = false;
        } else {
          res.disabled = true;
        }
      });
      return this.tableData;
    },
  },
  mounted() {
    this.getTenantList();
    this.getBaseArea(0);
  },

  methods: {
    cancle(){
      this.$refs.searchForm.resetFields();
      this.searchForm.sitesRemarks = ''
      this.tableData1 = []
      this.$router.push({path:'/siteList'})
    },
    changes(val) {
      this.searchForm.sitesRemarks = val.replace(/\s+/g, "")
    },
    changeName(val) {
      this.searchForm.sitesTyp = val.replace(/\s+/g, "")
    },
    change(val) {
      
      if (val && val.length == 1) {
        let arr = [];
        baseArea(val[val.length - 1]).then((res) => {
          if (res.code == 200) {
            res.data.forEach((item) => {
              arr.push({
                value: item.id,
                label: item.name,
                children: [],
              });
            });
          }
        });
        this.options.forEach((item) => {
          if (val[val.length - 1] == item.value) {
            this.$nextTick(() => {
              item.children = arr;
            });
          }
        });
      } else if (val && val.length == 2) {
        let arr = [];
        baseArea(val[val.length - 1]).then((res) => {
          if (res.code == 200) {
            res.data.forEach((item) => {
              arr.push({
                value: item.id,
                label: item.name,
              });
            });
          }
        });
        this.options.forEach((item) => {
          item.children.map((o) => {
            if (o.value == val[val.length - 1]) {
              this.$nextTick(() => {
                o.children = arr;
              });
            }
          });
        });
      }
    },
    selectable(row, index) {
      return row.disabled;
    },
    // 获取租户数据
    getTenantList() {
      tenantApi.queryIdNamePair().then((res) => {
        this.tenantList = res.data;
      });
    },
    //获取省
    getBaseArea(id) {
      baseArea(id).then((res) => {
        if (res.code == 200) {
          res.data.forEach((item) => {
            let obj = {
              value: item.id,
              label: item.name,
              children: [],
            };
            this.options.push(obj);
          });
          // 
          // this.options.forEach((items) => {
          //   
          //   if (!items.children.length) {
          //     baseArea(items.value).then((resp) => {
          //       if (resp.code == 200) {
          //         resp.data.forEach((item) => {
          //           let obj = {
          //             value: item.id,
          //             label: item.name,
          //             children: [],
          //           };
          //           items.children.push(obj);
          //         });
          //       }
          //     });
          //   } else {
          //     items.children.forEach((options) => {
          //       baseArea(options.value).then((resp) => {
          //         if (resp.code == 200) {
          //           resp.data.forEach((item) => {
          //             let obj = {
          //               value: item.id,
          //               label: item.name,
          //               children: [],
          //             };
          //             options.children.children.push(obj);
          //           });
          //         }
          //       });
          //     });
          //   }
          // });
          
        }
      });
    },
    //分页
    getPageList() { },
    //移除
    onCanle(row, index) {
      this.$confirm("此操作将移除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          
          this.tableData1.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSelectionChange() { },
    handleSelectionChangeDiaog(val) {
      
      this.checkList = val;
    },
    //添加設備
    handlerAdd() {
      if (!this.searchForm.tenantId) {
        this.$message({
          message: "请先选择租户",
          type: "warning",
        });
      } else {
        this.getList();
        this.dialogVisible = true;
      }
    },
    //保存
    //保存
    submitForm() {
      this.$refs.searchForm.validate((valid) => {
        if (valid) {
          if (!this.tableData1.length) {
            this.$message({
              message: "请至少添加一组设备",
              type: "warning",
            });
            return;
          } else {
            if (this.$route.query.id) {
              let data = {
                sitesRemarks: this.searchForm.sitesRemarks,
                sitesType: this.searchForm.sitesType,
                tenantId: this.searchForm.tenantId,
                baseAreaId:
                  this.searchForm.baseAreaId[
                  this.searchForm.baseAreaId.length - 1
                  ],
                deviceNodeIdList: this.deviceNodeIdList,
              };
              siteUpdate(data).then((res) => {
                
                if (res.code == 200) {
                  this.$message({
                    message: "修改成功",
                    type: "success",
                  });
                  this.$router.push({ path: "/siteList" });
                }
              });
            } else {
              let data = {
                sitesRemarks: this.searchForm.sitesRemarks,
                sitesType: this.searchForm.sitesType,
                tenantId: this.searchForm.tenantId,
                baseAreaId:
                  this.searchForm.baseAreaId[
                  this.searchForm.baseAreaId.length - 1
                  ],
                deviceNodeIdList: this.deviceNodeIdList,
              };
              siteSave(data).then((res) => {
                if (res.code == 200) {
                  if (res.data.code == 500) {
                    this.$message({
                      message: res.data.message,
                      type: "warning",
                    });
                    return;
                  } else {
                    this.$message({
                      message: "添加成功",
                      type: "success",
                    });
                    this.$router.push({ path: "/siteList" });
                  }
                }
              });
            }
          }
        } else {
          
          return false;
        }
      });
    },
    //选择设备
    submitOk() {
      if (!this.checkList.length) {
        this.$message({
          message: "请至少选择一组设备",
          type: "warning",
        });
        return;
      } else {
        this.dialogVisible = false;
        this.tableData1 = this.tableData1.concat(this.checkList);
        this.tableData1.forEach((item) => {
          this.deviceNodeIdList.push(item.nodeId);
        });
      }
    },
    //关闭
    close() {
      this.$refs.multipleTable.clearSelection();
      this.dialogVisible = false;
    },
    getPageList1() {
      this.getList();
    },
    qureySearch() {
      let p = { tenantId: this.searchForm.tenantId, isSites: 2 };
      const data = Object.assign({}, this.searchSite, p, {
        pageSize: 10,
        page: 1,
      });
      this.search(data);
    },
    getList() {
      let p = { tenantId: this.searchForm.tenantId, isSites: 2 };
      let data = Object.assign({}, this.searchSite, p, this.pagination);
      this.search(data);
    },
    search(data) {
      pageByTenantId(data).then((resp) => {
        
        let list = resp.data.list;
        list.forEach((item) => {
          item.disabled = true;
        });
        this.tableData = resp.data.list;
        this.pagination.total = resp.data.pagination.total;
      });
    },
  },
};
</script>

<style lang="scss">
.addSite {
  padding: 20px;
  .addForm {
    width: 100%;
    padding: 0 50px;
    margin: 0 auto;
  }
  .el-form-item__label {
    text-align: right !important;
  }
}
</style>